<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <dept-tree v-model="queryParams.deptId" @node-click="handleQuery" />
      </el-col>

      <!-- 用户列表 -->
      <el-col :lg="20" :xs="24">
        <page-search ref="searchRef" :search-config="searchConfig" @query-click="handleQueryClick"
          @reset-click="handleResetClick" />
        <!-- 列表 -->
        <page-content ref="contentRef" :content-config="contentConfig" @add-click="handleOpenModalClick"
          @edit-click="handleOpenModalClick" @export-click="handleExportClick" @search-click="handleSearchClick"
          @filter-change="handleFilterChange">
          <template #phone="scope">
            <el-text> {{ scope.row[scope.prop] }} </el-text>
            <copy-button v-if="scope.row[scope.prop]" :text="scope.row[scope.prop]" style="margin-left: 2px" />
          </template>
        </page-content>

        <!-- 新增或者编辑-->
        <page-modal ref="formModalRef" :modal-config="formModalConfig" @submit-click="handleSubmitClick">
          <template #password="scope">
            <el-input v-model="scope.formData[scope.prop]" type="password" placeholder="请输入密码" show-password />
          </template>
        </page-modal>


      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import UserAPI, { UserForm } from "@/api/user"
import type { IObject } from "@/components/CURD/types"
import usePage from "@/components/CURD/usePage"
import formModalConfig from "./config/form"
import contentConfig from "./config/content"
import searchConfig from "./config/search"


const {
  searchRef,
  contentRef,
  formModalRef,
  handleQueryClick,
  handleResetClick,
  handleSubmitClick,
  handleExportClick,
  handleSearchClick,
  handleFilterChange,
} = usePage()

/** 用户查询参数  */
const queryParams = reactive<any>({
  deptId: undefined,
})

/** 查询 */
function handleQuery(deptId: number) {
  handleFilterChange(queryParams)
}

// 新增或者修改表单
async function handleOpenModalClick(row: IObject = {}) {
  let formData: UserForm = {
    enabled: 1,
    gender: 'M'
  }
  if (row.user_id) {
    // 根据id获取数据进行填充
    const res = await UserAPI.findById(row.user_id)
    if (res.status === 200) {
      formData = res.data[0]
      if (formData.role_ids) {
        formData.role_ids = JSON.parse(formData.role_ids)
      }
    }
  }
  formModalRef.value?.setFormItemConfig({ "password": { hidden: row.user_id ? true : false, rules: [{ required: row.user_id ? false : true }] } })
  formModalRef.value?.setModalVisible(formData)
}
</script>
